package com.senken.commons.shiro;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.senken.entity.SkUser;
import com.senken.service.ISkRoleService;
import com.senken.service.ISkUserService;







public class ShiroDbRealm extends  AuthorizingRealm{

	private static final Logger LOGGER = LogManager.getLogger(ShiroDbRealm.class);

	


	
	@Autowired
	private ISkUserService userservice;
	@Autowired
	private ISkRoleService roleservice;
	
	
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		LOGGER.info("Shiro权限认证");
		ShiroUser shiroUser = (ShiroUser) principals.getPrimaryPrincipal();
        List<Integer> roleList = shiroUser.roleList;
        Set<String> urlSet = new HashSet<String>();
        for (Integer roleid : roleList) {
        	List<Map<Long, String>> resourelist = roleservice.selectResourceListByRoleId(roleid);
        	if(resourelist!=null){
        		for (Map<Long, String> map : resourelist) {
        			urlSet.add(map.get("url"));
				}
        	}
		}
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addStringPermissions(urlSet);
        return info;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
		LOGGER.info("Shiro开始登录认证");  
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		SkUser user = userservice.selectByUsername(token.getUsername());
		if(user==null){
			//账号不存在
			return null;
		}
		List<Integer> rolelist = roleservice.selectRoleIdByUserId(user.getUserId());
		ShiroUser shiroUser = new ShiroUser(user.getUserId(), user.getUsername(),rolelist,user.getNickname());
		return new SimpleAuthenticationInfo(shiroUser, user.getPassword().toCharArray(), getName());
	}

}
